<template>
  <div class="chat-container">
    <div class="chat-header">
      <h2>AI恋爱大师</h2>
      <div class="back-btn" @click="goBack">返回主页</div>
    </div>
    <div class="chat-messages" ref="messageContainer">
      <chat-message
        v-for="(msg, index) in messages"
        :key="index"
        :content="msg.content"
        :time="msg.time"
        :isUser="msg.isUser"
        :isTyping="msg.isTyping"
        @typing-complete="onTypingComplete(index)"
      />
    </div>
    <chat-input :isLoading="isLoading" @send="sendMessage" />
  </div>
</template>

<script>
import ChatMessage from '../components/ChatMessage.vue'
import ChatInput from '../components/ChatInput.vue'
import { apiService } from '../api'
import { generateUUID, formatTime } from '../utils'

export default {
  name: 'LoveApp',
  components: {
    ChatMessage,
    ChatInput
  },
  data() {
    return {
      chatId: '',
      messages: [],
      isLoading: false,
      eventSource: null,
      currentMessage: '',
      aiResponse: '',
      currentAiMessageIndex: -1
    }
  },
  created() {
    this.chatId = generateUUID()
    this.addMessage('你好，我是你的AI恋爱大师。今天想聊些什么呢？', false)
  },
  methods: {
    goBack() {
      this.$router.push('/')
    },
    addMessage(content, isUser) {
      const message = {
        content,
        time: formatTime(new Date()),
        isUser,
        isTyping: !isUser // 只有AI消息才有打字效果
      }
      
      this.messages.push(message)
      
      if (!isUser) {
        // 记录当前AI消息的索引
        this.currentAiMessageIndex = this.messages.length - 1
      }
      
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      return this.messages.length - 1
    },
    onTypingComplete(index) {
      // 打字效果完成后，更新消息状态
      if (index < this.messages.length) {
        this.messages[index].isTyping = false
      }
    },
    scrollToBottom() {
      const container = this.$refs.messageContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    sendMessage(message) {
      // 保存当前消息
      this.currentMessage = message
      
      // 添加用户消息
      this.addMessage(message, true)
      this.isLoading = true
      this.aiResponse = ''
      
      // 关闭之前的连接
      this.closeEventSource()
      
      // 预先添加一个空的AI消息，用于实时显示
      const aiMessageIndex = this.addMessage('', false)
      
      try {
        // 创建SSE连接
        this.eventSource = apiService.getLoveAppChatSSE(message, this.chatId)
        
        this.eventSource.onmessage = (event) => {
          const data = event.data
          if (data) {
            // 累积响应
            this.aiResponse += data
            
            // 实时更新AI消息内容
            if (aiMessageIndex >= 0 && aiMessageIndex < this.messages.length) {
              this.messages[aiMessageIndex].content = this.aiResponse
              this.$nextTick(() => {
                this.scrollToBottom()
              })
            }
          }
        }
        
        // 连接成功时触发
        this.eventSource.onopen = () => {
          console.log('SSE连接已建立')
        }
        
        // 错误处理
        this.eventSource.onerror = (error) => {
          console.error('SSE错误:', error)
          
          // 关闭连接并重置状态
          this.closeEventSource()
          
          // 如果已经收到部分响应，保留显示
          if (this.aiResponse && aiMessageIndex >= 0) {
            this.messages[aiMessageIndex].isTyping = false
          } else if (aiMessageIndex >= 0) {
            // 如果没有收到任何响应，显示错误消息
            this.messages[aiMessageIndex].content = '抱歉，发生了错误，请稍后再试。'
            this.messages[aiMessageIndex].isTyping = false
          }
        }
      } catch (error) {
        console.error('连接错误:', error)
        this.isLoading = false
        
        if (aiMessageIndex >= 0) {
          this.messages[aiMessageIndex].content = '抱歉，连接服务器时出错，请稍后再试。'
          this.messages[aiMessageIndex].isTyping = false
        }
      }
    },
    closeEventSource() {
      if (this.eventSource) {
        this.eventSource.onmessage = null
        this.eventSource.onerror = null
        this.eventSource.onopen = null
        this.eventSource.close()
        this.eventSource = null
        this.isLoading = false
      }
    }
  },
  beforeUnmount() {
    // 组件销毁前关闭SSE连接
    this.closeEventSource()
  }
}
</script>

<style scoped>
.back-btn {
  position: absolute;
  left: 15px;
  top: 15px;
  cursor: pointer;
  font-size: 14px;
  color: #fff;
  text-decoration: underline;
}
</style> 